package pers.cz.mock;

import pers.cz.config.Config;
import pers.cz.util.ICollectGenerator;
import redis.clients.jedis.Jedis;

import java.util.Map;

/**
 * @program: postgirl-collection-client
 * @description: ParamsAndReturnThread
 * @author: Cheng Zhi
 * @create: 2022-03-02 14:37
 **/
public class ParamsAndReturnThread implements ICollectGenerator {

    private String request;
    private String response;
    private String methodName;
    private Jedis resource;
    private String targetMethod;
    private String traceId;

    public ParamsAndReturnThread(String targetMethod, String request, String response, String methodName, Jedis resource, String traceId) {
        this.request = request;
        this.response = response;
        this.methodName = methodName;
        this.resource = resource;
        this.targetMethod = targetMethod;
        this.traceId = traceId;
    }

    @Override
    public void run() {
        try {
            insertRedis(targetMethod, request, response, methodName, traceId);
        } finally {
            resource.close();
        }
    }

    /**
     * 插入redis
     * @param request
     * @param response
     * @param methodName
     */
    private void insertRedis(String targetMethod, String request, String response, String methodName, String traceId) {
        try {
            System.out.println("插入数据库开始");
            Map<String, String> cacheMap = Config.getConfig().getsysConfig();
            String key = cacheMap.get("redis.MethodCollectionQueue");           // redisc存储key
            String source = cacheMap.get("source");                             // redis数据源

            //int requestHash = request.hashCode();                               // 对请求取hash
            //int responseHash = response.hashCode();                             // 对结果取hash


            this.resource.lpush(key, methodName + "||" + source + "||" + request + "||" + response + "||" + targetMethod + "||" + request.hashCode() + "||" + response.hashCode() + "||" + traceId);
        } catch (Exception e) {
            System.out.println("------插入数据库异常-------");
        }
    }
}
